<template>
  <CustomDialog :options="options" @open="open" @confirm="handleConfirm">
    <div class="wrapper">
      <div v-show="!selectType" class="wrapper-left my-button-group">
        <div v-for="renderType in renderTypeList" :key="renderType.text">
          <el-button
            style="width: 100%; justify-content: flex-start"
            text
            @click="changeType(renderType)"
          >
            {{ renderType.text }}
          </el-button>
        </div>
      </div>
      <div v-show="selectType" class="wrapper-left">
        <div class="search-bar mb0">
          <el-form :model="formData" :inline="true">
            <el-form-item prop="campus" style="margin-right: 0">
              <el-button text style="padding-left: 0" @click="selectType = null">
                <el-icon class="el-icon--right">
                  <ArrowLeft />
                </el-icon>
                &ensp;返回
              </el-button>
            </el-form-item>
            <el-form-item prop="name" style="margin-right: 0px">
              <el-input
                v-model="formData['name']"
                placeholder="请输入"
                style="width: 228px"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="tree-wrapper">
          <el-tree
            ref="treeRef"
            v-loading="loading"
            :data="treeData"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
            :filter-node-method="filterNode"
            @checkChange="handleCheckChange"
          />
        </div>
      </div>
      <div class="wrapper-right">
        <div class="wrapper-right-top">
          <div>已选择{{ selectedUsers.length }}人</div>
          <el-button type="primary" link style="padding: 0px" @click="resetSelectedUsers">
            重置
          </el-button>
        </div>
        <div class="selected-member">
          <div v-for="(user, idx) in selectedUsers" :key="user.id" class="member-item">
            <div>{{ user.nickname }}</div>
            <el-icon class="close-icon" @click="deleteUser(user, idx)">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<script>
  import {
    getUserListByArea,
    getUserListByGroup,
    getUserListByRole,
    getUserListByWard,
  } from '@/api/system/user.js';
  import { getUserGroupList } from '@/api/system/QCGroup.js';
  import CustomDialog from '@/components/CustomDialog/index.vue';
  import { nanoid } from '@/utils';
  export default {
    components: {
      CustomDialog,
    },
    props: {
      whereToUse: {
        type: String,
        default: 'default',
      },
      options: {
        type: Object,
        required: true,
        default() {
          return {
            width: 636,
            title: '选择人员',
            visible: false,
            curSelectedUsers: [],
          };
        },
      },
    },
    emits: ['changeSelectedUsers'],

    data() {
      const renderTypeList = [
        { text: '按片区选择', fn: getUserListByArea, params: {} },
        { text: '按护理单元选择', fn: getUserListByWard, params: {} },
        { text: '按角色选择', fn: getUserListByRole, params: {} },
        { text: '按职务选择', fn: getUserListByGroup, params: { group: 'system_nurse_job' } },
        { text: '按职称选择', fn: getUserListByGroup, params: { group: 'system_nurse_title' } },
        { text: '按层级选择', fn: getUserListByGroup, params: { group: 'system_nurse_hierarchy' } },
      ];
      if (this.whereToUse === 'messageTemplate') {
        renderTypeList.push({ text: '按用户组选择', fn: getUserGroupList, params: {} });
      }

      return {
        formData: {
          name: '',
        },
        defaultProps: {
          children: 'children',
          label: 'label',
        },

        renderTypeList,
        selectedUsers: [], // 已选择的数据

        selectType: null, // 选择类型
        treeData: [],
        nodeList: [],
        loading: false,
      };
    },
    watch: {
      selectType(val) {
        this.treeData = [];
        if (!val) return;
        this.initTreeData(val);
      },
      'formData.name': function (val) {
        this.$refs['treeRef']?.filter(val || '');
      },
    },
    methods: {
      open() {
        this.selectType = null;
        this.selectedUsers = this.options.curSelectedUsers;
      },
      close() {
        // eslint-disable-next-line vue/no-mutating-props
        this.options.visible = false;
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.includes(value);
      },
      /** 重置已选用户 */
      resetSelectedUsers() {
        this.selectedUsers = [];
        this.$refs['treeRef'].setCheckedKeys([]);
      },
      // 初始化用户树
      initTreeData(type) {
        this.loading = true;
        type
          .fn(type.params)
          .then(async (res) => {
            this.treeData = (res.data || []).map((i) => ({
              id: nanoid(6),
              type: 'group',
              label: `${i.label}(${(i.options || []).length}人)`,
              children: (i.options || []).map((j) => ({
                type: 'user',
                label: j.label,
                id: j.value,
              })),
            }));
            console.log(this.$refs['treeRef']);

            // 回显勾选
            // const checkedKeys = this.selectedUsers.map(i => i.id)
            // this.$refs['treeRef'].setCheckedKeys(checkedKeys)

            // 回显勾选(id相同的用户全部勾选)
            await this.$nextTick();
            this.nodeList = this.getAllNodeList();
            const checkedNodes = this.nodeList.filter((i) =>
              this.selectedUsers.find((j) => j.id === i.data.id),
            );
            checkedNodes.forEach((node) => node.setChecked(true, true));
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 获取全部tree全部节点
      getAllNodeList() {
        const checkedNodes = [];
        const traverse = function (node) {
          const childNodes = node.root ? node.root.childNodes : node.childNodes;

          childNodes.forEach((child) => {
            checkedNodes.push(child);
            traverse(child);
          });
        };
        traverse(this.$refs['treeRef']);
        return checkedNodes;
      },
      handleCheckChange(data, checked) {
        if (data.type === 'group') return;
        const index = this.selectedUsers.findIndex((i) => i.id === data.id);
        if (checked) {
          if (index === -1) {
            this.selectedUsers.push({ id: data.id, nickname: data.label });
          }
        } else {
          if (index > -1) {
            const count = this.$refs['treeRef']
              .getCheckedNodes()
              .reduce((acc, cur) => (cur.id === data.id ? ++acc : acc), 0);
            // count代表移除当前勾选状态的id还有几个，如果没有再执行selectedUsers删除
            if (count === 0) this.selectedUsers.splice(index, 1);
          }
        }
      },
      // 从右侧点击删除用户
      deleteUser(user, idx) {
        console.log(user);
        // 删除左侧用户勾选状态
        // const index = this.selectedUsers.findIndex(i => i.id === user.id)
        // this.selectedUsers.splice(index, 1)
        // this.$refs['treeRef'].setChecked(user.id, false, true)

        if (!this.selectType) {
          // 如果未点进人员分组，则直接删除
          this.selectedUsers.splice(idx, 1);
        }

        // 删除左侧用户勾选状态(删除左侧全部目标id相同的节点)
        this.nodeList
          .filter((i) => i.data.id === user.id)
          .forEach((node) => node.setChecked(false, false));
      },
      changeType(renderType) {
        this.selectType = renderType;
      },
      handleConfirm() {
        if (this.selectedUsers.length === 0) {
          this.$message.warning('请选择人员');
          return;
        }
        this.$emit('changeSelectedUsers', this.selectedUsers);
        this.close();
      },
    },
  };
</script>

<style lang="scss" scoped>
  .search-bar {
    padding: 0 0 0 3px;
  }
  .wrapper {
    line-height: 1.5;
    width: 100%;
    /* padding: 20px; */
    height: 482px;
    display: flex;
    border-bottom: 1px solid #ebebeb;
    .wrapper-left {
      flex: none;
      height: 100%;
      width: 336px;
      background: #fff;
      .tree-wrapper {
        height: calc(100% - 128px);
        overflow: auto;
        padding: 0 20px;
      }
      &.my-button-group {
        padding-top: 30px;
      }
    }
    .wrapper-right {
      width: 300px;
      height: 100%;
      background: #f8f9f9;
      padding: 25px 20px;
      .wrapper-right-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
      }
      .selected-member {
        height: calc(100% - 32px);
        overflow: auto;
        .member-item {
          display: flex;
          justify-content: space-between;
          font-weight: 400;
          font-size: 14px;
          line-height: 140%;
          margin-bottom: 8px;
          color: #333333;
          .close-icon {
            cursor: pointer;
            color: #999999;
          }
        }
      }
    }
  }
</style>
